package com.dingup.provider.service.student.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingup.api.adapter.student.StudentCourseInformationAdapter;
import com.dingup.api.enums.ClassUserTypeEnum;
import com.dingup.api.enums.ExamTypeEnum;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.api.model.classInfo.ClassUserInfo;
import com.dingup.api.model.lesson.LessonInfo;
import com.dingup.api.model.student.Student;
import com.dingup.api.model.student.StudentCourseInformation;
import com.dingup.api.model.sys.SysUser;
import com.dingup.provider.mapper.*;
import com.dingup.provider.service.classInfo.ClassInfoService;
import com.dingup.provider.service.classInfo.ClassUserInfoService;
import com.dingup.provider.service.lesson.LessonService;
import com.dingup.provider.service.permission.PermissionCacheService;
import com.dingup.provider.service.student.StudentCourseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/8/15.
 */
@Service
public class StudentCourseServiceImpl implements StudentCourseService {

    private final String IS_STUDENT_PRICE_PERMISSION = "isStudentPricePermission";

    @Autowired
    StudentCourseInformationMapper studentCourseInformationMapper;
    @Autowired
    LessonService lessonService;
    @Autowired
    ClassInfoService classInfoService;
    @Autowired
    LessonInfoMapper lessonInfoMapper;
    @Autowired
    ClassInfoMapper classInfoMapper;
    @Autowired
    ClassUserInfoMapper classUserInfoMapper;
    @Autowired
    PermissionCacheService permissionCacheService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    ClassUserInfoService classUserInfoService;

    @Override
    public void saveStudentCourse(StudentCourseInformation studentCourseInformation,String createUserId) {
        //设置了班级则 将学生添加到该班级中
        if (studentCourseInformation.getClassId() != null){
            ClassUserInfo student = new ClassUserInfo();
            student.setClassId(studentCourseInformation.getClassId());
            student.setType(ClassUserTypeEnum.STUDENT);
            student.setUserId(studentCourseInformation.getUserId());
            student.setCreateUserId(createUserId);
            student.setCreateTime(new Date());
            List<ClassUserInfo> needInsert = new ArrayList<>();
            needInsert.add(student);
            classUserInfoService.needInsert(needInsert, createUserId, studentCourseInformation.getClassId());
        }
        studentCourseInformationMapper.insertSelective(studentCourseInformation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudentCourse(StudentCourseInformation studentCourseInformation,String createUserId) {
        StudentCourseInformation old = studentCourseInformationMapper.selectByPrimaryKey(studentCourseInformation.getId());
        //添加动作
        if(old.getClassId() ==  null && studentCourseInformation.getClassId() != null){
            ClassUserInfo student = new ClassUserInfo();
            student.setClassId(studentCourseInformation.getClassId());
            student.setType(ClassUserTypeEnum.STUDENT);
            student.setUserId(studentCourseInformation.getUserId());
            student.setCreateUserId(createUserId);
            List<ClassUserInfo> needInsert = new ArrayList<>();
            if (student != null) {
                needInsert.add(student);
            }
            classUserInfoService.needInsert(needInsert,createUserId,studentCourseInformation.getClassId());
            //修改动作
        }else if (old.getClassId() !=  null && studentCourseInformation.getClassId() != null && !old.getClassId().equals(studentCourseInformation.getClassId())){
            ClassUserInfo param = new ClassUserInfo();
            param.setUserId(old.getUserId());
            param.setClassId(old.getClassId());
            param.setType(ClassUserTypeEnum.STUDENT);
            ClassUserInfo student = classUserInfoMapper.getClassUserInfo(param);
            List<ClassUserInfo> needDelete = new ArrayList<>();
            if (student != null) {
                needDelete.add(student);
            }
            classUserInfoService.needDelete(needDelete,createUserId,old.getClassId());
            student.setId(null);
            student.setClassId(studentCourseInformation.getClassId());
            student.setCreateUserId(createUserId);
            student.setCreateTime(new Date());
            List<ClassUserInfo> needInsert = new ArrayList<>();
            if (student != null) {
                needInsert.add(student);
            }
            classUserInfoService.needInsert(needInsert,createUserId,studentCourseInformation.getClassId());
        }else if (old.getClassId() !=  null && studentCourseInformation.getClassId() == null){
            //删除动作
            ClassUserInfo param = new ClassUserInfo();
            param.setUserId(old.getUserId());
            param.setClassId(old.getClassId());
            param.setType(ClassUserTypeEnum.STUDENT);
            ClassUserInfo student = classUserInfoMapper.getClassUserInfo(param);
            List<ClassUserInfo> needDelete = new ArrayList<>();
            if (student != null) {
                needDelete.add(student);
            }
            classUserInfoService.needDelete(needDelete,createUserId,old.getClassId());
        }
        studentCourseInformationMapper.updateByPrimaryKeySelective(studentCourseInformation);
    }

    @Override
    public Map<String,List<StudentCourseInformationAdapter>> getStudentCourseByStudentId(String studentId, String userAccount) {
        List<StudentCourseInformationAdapter> informations = studentCourseInformationMapper.getByUserId(studentId);
        informations.parallelStream().forEach(
                s->{
                    //如果没有销售或者 没有成单金额   则是缺少承担信息
                    if (StringUtils.isEmpty(s.getSalerId()) || s.getContributionAmount() == null || s.getContributionAmount() == 0){
                        s.setIfLackWholeMsg(true);
                    }else{
                        s.setIfLackWholeMsg(false);
                    }
                    if (s.getClassId() == null){
                        s.setIfLackClassMsg(true);
                    }
                    if (!StringUtils.isEmpty(s.getExam())){
                        s.setExamName(ExamTypeEnum.getDescription(s.getExam()));
                    }
                    //是否有权限查看缴费金额
                    if (!permissionCacheService.getPermission(userAccount,IS_STUDENT_PRICE_PERMISSION)){
                        s.setContributionAmount(null);
                    }
                    if (s.getOrderTime() != null) {
                        s.setOrderTimeStamp(s.getOrderTime().getTime());
                    }
                }

        );
        Map<Boolean,List<StudentCourseInformationAdapter>> group = informations.stream().collect(Collectors.groupingBy(StudentCourseInformationAdapter::getIfLackWholeMsg));
        Map<String,List<StudentCourseInformationAdapter>> res = new HashMap<>();
        res.put("lack",group.get(true));
        res.put("whole",group.get(false));
        return  res;
    }

    @Override
    public List<StudentCourseInformationAdapter> getStudentCourseByStudentId(String studentId) {
        List<StudentCourseInformationAdapter> informations = studentCourseInformationMapper.getByUserId(studentId);
        return informations;
    }

    @Override
    public Boolean ifHasUnFinishLessonMsg(Student student) {
        List<StudentCourseInformation> courseInformations = studentCourseInformationMapper.getByContributionAmountOrSalerIsNull(student.getStudentId());
        if (courseInformations != null && courseInformations.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean ifHasNullClassMsg(Student student) {
        List<StudentCourseInformation> courseInformations = studentCourseInformationMapper.getByClassIdIsNull(student.getStudentId());
        if (courseInformations != null && courseInformations.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public StudentCourseInformationAdapter getById(Integer id) {
        StudentCourseInformation course = studentCourseInformationMapper.selectByPrimaryKey(id);
        StudentCourseInformationAdapter res = JSONObject.parseObject(JSONObject.toJSONString(course),StudentCourseInformationAdapter.class);
        if (course.getLessonId() != null){
            LessonInfo lessonInfo = lessonInfoMapper.selectByPrimaryKey(course.getLessonId());
            if (lessonInfo != null && !StringUtils.isEmpty(lessonInfo.getExam())){
                lessonInfo.setExamName(ExamTypeEnum.getDescription(lessonInfo.getExam()));
            }
            res.setLesson(lessonInfo);
        }
        if (course.getClassId() != null){
            ClassInfo classInfo =  classInfoService.getCourseClassInfo(course.getClassId());
            res.setClassInfo(classInfo);
        }
        if (!StringUtils.isEmpty(course.getSalerId())){
            SysUser saler = sysUserMapper.selectByPrimaryKey(course.getSalerId());
            res.setSalerName(saler.getUserName());
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteStudentCourse(Integer id) {
        StudentCourseInformation course = studentCourseInformationMapper.selectByPrimaryKey(id);
        if (!StringUtils.isEmpty(course.getSalerId()) && course.getContributionAmount() != null && course.getContributionAmount() != 0
                && course.getClassId() != null){
            ClassUserInfo param = new ClassUserInfo();
            param.setType(ClassUserTypeEnum.STUDENT);
            param.setUserId(course.getUserId());
            param.setClassId(course.getClassId());
            ClassUserInfo classUserInfo = classUserInfoMapper.getClassUserInfo(param);
            if (classUserInfo != null){
                List<ClassUserInfo> needDelete = new ArrayList<>();
                needDelete.add(classUserInfo);
                classUserInfoService.needDelete(needDelete, null, classUserInfo.getClassId());
            }
        }
        studentCourseInformationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public StudentCourseInformation getByStudentIdAndClassId(String studentId, Integer classId, String userAccount) {
        StudentCourseInformation course = studentCourseInformationMapper.getByStudentIdAndClassId(studentId, classId);
        if (course != null) {
            //是否有权限查看缴费金额
            if (!permissionCacheService.getPermission(userAccount, IS_STUDENT_PRICE_PERMISSION)) {
                course.setContributionAmount(null);
            }
            //如果没有销售或者 没有成单金额   则是缺少承担信息
            if (StringUtils.isEmpty(course.getSalerId()) || course.getContributionAmount() == null || course.getContributionAmount() == 0) {
                return null;
            }
        }
        return course;
    }
}
